// 主题管理工具

// 主题枚举
export const THEME = {
  LIGHT: 'light',
  DARK: 'dark',
  AUTO: 'auto'
}

// 获取系统主题偏好
export const getSystemTheme = () => {
  return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches 
    ? THEME.DARK 
    : THEME.LIGHT
}

// 设置 Element Plus 主题
const setElementPlusTheme = (theme) => {
  const htmlElement = document.documentElement
  
  if (theme === THEME.DARK) {
    htmlElement.classList.add('dark')
  } else if (theme === THEME.LIGHT) {
    htmlElement.classList.remove('dark')
  } else {
    // AUTO mode
    const systemTheme = getSystemTheme()
    if (systemTheme === THEME.DARK) {
      htmlElement.classList.add('dark')
    } else {
      htmlElement.classList.remove('dark')
    }
  }
}

// 设置主题到 DOM
export const setTheme = (theme) => {
  const htmlElement = document.documentElement
  
  // 清除所有主题类
  htmlElement.classList.remove(THEME.LIGHT, THEME.DARK)
  
  if (theme === THEME.AUTO) {
    // 跟随系统
    const systemTheme = getSystemTheme()
    htmlElement.classList.add(systemTheme)
    // 监听系统主题变化
    watchSystemTheme()
  } else {
    // 固定主题
    htmlElement.classList.add(theme)
    // 移除系统主题监听
    unwatchSystemTheme()
  }
  
  // 设置 Element Plus 主题
  setElementPlusTheme(theme)
  
  // 保存到 localStorage
  localStorage.setItem('theme', theme)
}

// 监听系统主题变化
let systemThemeMediaQuery = null
export const watchSystemTheme = () => {
  if (window.matchMedia) {
    systemThemeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    systemThemeMediaQuery.addEventListener('change', handleSystemThemeChange)
  }
}

// 取消监听系统主题变化
export const unwatchSystemTheme = () => {
  if (systemThemeMediaQuery) {
    systemThemeMediaQuery.removeEventListener('change', handleSystemThemeChange)
    systemThemeMediaQuery = null
  }
}

// 处理系统主题变化
const handleSystemThemeChange = (e) => {
  const htmlElement = document.documentElement
  htmlElement.classList.remove(THEME.LIGHT, THEME.DARK)
  htmlElement.classList.add(e.matches ? THEME.DARK : THEME.LIGHT)
  
  // 同步 Element Plus 主题
  if (e.matches) {
    htmlElement.classList.add('dark')
  } else {
    htmlElement.classList.remove('dark')
  }
}

// 初始化主题
export const initTheme = () => {
  const savedTheme = localStorage.getItem('theme') || THEME.AUTO
  setTheme(savedTheme)
}